package com.cms.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cms.common.QueryPageParam;
import com.cms.common.Result;
import com.cms.entity.Goods;
import com.cms.entity.User;
import com.cms.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @GetMapping("/list")
    public Result list(@RequestParam String goodsName, @RequestParam String goodsTypeId, @RequestParam String sourceId){
        LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(goodsName) && !"null".equals(goodsName)) {
            lambdaQueryWrapper.like(Goods::getGoodsName, goodsName);
        }
        if (StringUtils.isNotBlank(goodsTypeId) && !"null".equals(goodsTypeId)) {
            lambdaQueryWrapper.eq(Goods::getGoodsTypeId, goodsTypeId);
        }
        if (StringUtils.isNotBlank(sourceId) && !"null".equals(sourceId)) {
            lambdaQueryWrapper.eq(Goods::getSourceId, sourceId);
        }

        return Result.suc(goodsService.list(lambdaQueryWrapper));
    }

    // 新增
    @PostMapping("/save")
    public Result save(@RequestBody Goods goods) {
        return goodsService.save(goods) ? Result.suc() : Result.fail();
    }

    // 更新
    @PostMapping("/update")
    public Result update(@RequestBody Goods goods) {
        return goodsService.updateById(goods) ? Result.suc() : Result.fail();
    }

    // 删除
    @GetMapping("/del")
    public Result del(@RequestParam String id) {
        return goodsService.removeById(id) ? Result.suc() : Result.fail();
    }
    /*
    @DeleteMapping("/del/{id}")
    public Result del(@PathVariable String id){
        return goodsService.removeById(id)?Result.suc():Result.fail();
    }
*/

    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String goodsName = (String) param.get("goodsName");
        String goodsTypeId = (String) param.get("goodsTypeId");
        String storageId = (String) param.get("storageId");
        String sourceId = (String) param.get("sourceId");

        System.out.println(goodsTypeId);
        Page<Goods> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(goodsName) && !"null".equals(goodsName)) {
            lambdaQueryWrapper.like(Goods::getGoodsName, goodsName);
        }
        if (StringUtils.isNotBlank(goodsTypeId) && !"null".equals(goodsTypeId)) {
            lambdaQueryWrapper.eq(Goods::getGoodsTypeId, goodsTypeId);
        }
        if (StringUtils.isNotBlank(storageId) && !"null".equals(storageId)) {
            lambdaQueryWrapper.eq(Goods::getStorageId, storageId);
        }
        if (StringUtils.isNotBlank(sourceId) && !"null".equals(sourceId)) {
            lambdaQueryWrapper.eq(Goods::getSourceId, sourceId);
        }

//        IPage result = goodsService.page(page, lambdaQueryWrapper); // 你mapper的方法都可以删了
//        System.out.println();
//        return Result.suc(result.getRecords(), result.getTotal());
        IPage result = goodsService.pageCC(page, lambdaQueryWrapper); // 你mapper的方法都可以删了
        System.out.println();
        return Result.suc(result.getRecords(), result.getTotal());
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库查询出所有的数据
        List<Goods> list = goodsService.list();
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名，如果把这些注释掉，导出的表头就是数据库的字段
//        writer.addHeaderAlias("id","用户ID");
//        writer.addHeaderAlias("avatarUrl","头像地址");
//        writer.addHeaderAlias("no","账号");
//        writer.addHeaderAlias("name","用户名");
//        writer.addHeaderAlias("password","密码");
//        writer.addHeaderAlias("age","年龄");
//        writer.addHeaderAlias("sex","性别");
//        writer.addHeaderAlias("phone","电话号码");
//        writer.addHeaderAlias("roleId","权限");
//        writer.addHeaderAlias("isvalid","认证");

        //一次性写出list内的对象到excel,使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("货物信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();

    }

    /**
     * 导出接口
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //当表头是英文名才能用，导出的时候注释掉别名就好了
        List<Goods> list = reader.readAll(Goods.class);
        goodsService.saveBatch(list);
        return true;
    }
    /**
     *
     */
    @GetMapping("/{id}")
    public ResponseEntity<Goods> getGoodsById(@PathVariable Integer id) {
        // 根据 ID 查询数据库获取单个 Goods 对象
       // Goods goods = goodsService.getGoodsById(id);
        Goods goods = goodsService.getById(id);

        if (goods != null) {
            return ResponseEntity.ok(goods);  // 返回成功响应和 Goods 对象
        } else {
            return ResponseEntity.notFound().build();  // 返回 404 响应
        }
    }
}

/*
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    //新增
    @PostMapping("/save")
    public Result save(@RequestBody Goods goods){
        return goodsService.save(goods)?Result.suc():Result.fail();
    }

    //更新
    @PostMapping("/update")
    public Result update(@RequestBody Goods goods){
        return goodsService.updateById(goods)?Result.suc():Result.fail();
    }

    //删除
    @GetMapping("/del")
    public Result del(@RequestParam String id){
        return goodsService.removeById(id)?Result.suc():Result.fail();
    }

    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String goodsName = (String)param.get("goodsName");
        String goodsTypeId = (String)param.get("goodsTypeId");
        String storageId = (String)param.get("storageId");

        Page<Goods> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(goodsName) && !"null".equals(goodsName)){
            lambdaQueryWrapper.like(Goods::getGoodsName,goodsName);
        }
        if(StringUtils.isNotBlank(goodsTypeId) && !"null".equals(goodsTypeId)){
            lambdaQueryWrapper.eq(Goods::getGoodsTypeId,goodsTypeId);
        }
        if(StringUtils.isNotBlank(storageId) && !"null".equals(storageId)){
            lambdaQueryWrapper.eq(Goods::getStorageId,storageId);
        }

        IPage result = goodsService.pageCC(page,lambdaQueryWrapper);
        return Result.suc(result.getRecords(),result.getTotal());
    }
}
*/